// pages/player/player.js
let musiclist = []
let musicId = ''
let singleList = []
// 正在播放的歌曲index
let nowPlayingIndex = 0
// 获取全局唯一的背景音频管理器
const backgroundAudioManager = wx.getBackgroundAudioManager()


const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    picUrl: '',
    isPlaying: false, //false表示不播放true表示正在播放
    isLyricShow: false, //当前歌词是否显示
    lyric: '', //歌词
    isSame: false, //是否是同一首歌
    isFavorite: false, //是否被收藏
    modalShow: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    musicId = options.musicId
    nowPlayingIndex = options.index
    singleList = wx.getStorageSync('singleList')
    this.getPicUrl(options.musicId)
    this._loadMusicDetail(options.musicId)
    this.judgeFavorite()
  },

  getPicUrl(musicId) {
    wx.request({
      url: 'https://autumnfish.cn/song/detail?ids=' + musicId,
      success: ((res) => {
        const picUrl = res.data.songs[0].al.picUrl
        console.log(res)
        // picUrl2 = res.data.songs[0].al.picUrl
        this.setData({
          picUrl,
          isPlaying: true
        })
      }),
      fail: ((err) => {
        console.log(err)
      })
    })
  },


  _loadMusicDetail: function(musicId) {
    if (musicId == app.getPlayMusicId()) {
      this.setData({
        isSame: true
      })
    } else {
      this.setData({
        isSame: false
      })
    }
    if (!this.data.isSame) {
      backgroundAudioManager.stop();
    }
    this.getPicUrl(musicId)
    let music = singleList[nowPlayingIndex];
    console.log(singleList)
    console.log(music)
    wx.setNavigationBarTitle({
      title: music.name,
    })

    app.setPlayMusicId(musicId)

    wx.showLoading({
      title: '歌曲加载中',
    })
    wx.request({
      url: 'http://www.li11.wang/song/url?id=' + musicId,
      success: ((res) => {
        console.log(res.data.data[0].url)
        console.log(res)
        let musicurl = res.data.data[0].url
        if (res.data.data[0].url == null) {
          wx.showToast({
            title: '无权限播放',
          })
          return
        }
        if (!this.data.isSame) {
          backgroundAudioManager.src = musicurl;
          backgroundAudioManager.title = music.name;
          backgroundAudioManager.coverImgUrl = this.data.picUrl;
          // console.log(picUrl)
          backgroundAudioManager.singer = music.ar[0].name;
          backgroundAudioManager.epname = music.al.name;
        }
        this.setData({
          isPlaying: true
        })
        wx.hideLoading()

        // 加载歌词
        wx.request({
          url: 'http://www.li11.wang/lyric?id=' + musicId,
          success: ((res) => {
            console.log(res)
            let lyric = '暂无歌词'
            const lrc = res.data.lrc.lyric
            if (lrc) {
              lyric = lrc
            }
            this.setData({
              lyric
            })
          })
        })
      })
    })
  },

  togglePlaying() {
    // 正在播放
    if (this.data.isPlaying) {
      backgroundAudioManager.pause()
    } else {
      backgroundAudioManager.play()
    }
    this.setData({
      isPlaying: !this.data.isPlaying
    })
  },



  onPrev() {
    nowPlayingIndex--
    if (nowPlayingIndex < 0) {
      nowPlayingIndex = singleList.length - 1
    }
    this._loadMusicDetail(singleList[nowPlayingIndex].id)
    musicId = singleList[nowPlayingIndex].id
    this.judgeFavorite()
  },

  onNext() {
    nowPlayingIndex++
    if (nowPlayingIndex === singleList.length) {
      nowPlayingIndex = 0
    }

    this._loadMusicDetail(singleList[nowPlayingIndex].id)
    musicId = singleList[nowPlayingIndex].id
    this.judgeFavorite()
  },

  onChangeLyricShow() {
    this.setData({
      isLyricShow: !this.data.isLyricShow
    })
  },

  timeUpdate(event) {
    console.log(event)
    this.selectComponent('.lyric').update(event.detail.currentTime)
  },


  onPlay() {
    this.setData({
      isPlaying: true,
    })
  },

  onPause() {
    this.setData({
      isPlaying: false,
    })
  },

  cancelFavorites(){
    wx.getStorage({
      key: 'user_id',
      success: (res) => {
        this.deleteMusic(res.data)
      },
    })  
    // this.setData({
    //   isFavorite: false,
    // })
  },
  
  deleteMusic(user_id){
    wx.request({
      url: 'http://127.0.0.1:8000/delete_music/',
      method: 'POST',
      data: {
        user_id,
        musicId
      },
      success: ((res) =>{
        console.log(res)
        this.setData({
          isFavorite: false,
        })
        if (res.data.err==200){
          wx.showToast({
            title: res.data.errmsg,
          })
        }
      })
    })
  },

  collectMusic(user_id){
    let music = singleList[nowPlayingIndex]
    console.log(music)
    let special_name = music.al.name
    let music_name = music.name
    let picurl = music.al.picUrl
    let singer_name = music.ar[0].name

    let mv = music.mv || music.mvid
    // let alia = music.alias
    let alia = music.alia || music.alias
    if (alia=music.alias||music.alia){
      if(alia.length==1){
        var music_othername = alia.name || alia[0]
      }else{
        var music_othername = 0
      }
    }
    wx.request({
      url: `http://127.0.0.1:8000/collect_music/`,
      method: 'POST',
      data: {
        user_id,
        musicId,
        special_name,
        music_name,
        picurl,
        singer_name,
        mv,
        music_othername,
      },
      success: ((res) =>{
        console.log(res)
        wx.showToast({
          title: res.data.errmsg,
        })
      })
    })
  },

  judgeMusic(user_id){
    wx.request({
      url: 'http://127.0.0.1:8000/judge_music/',
      method: 'POST',
      data: {
        user_id,
        musicId,
      },
      success: ((res) =>{
        console.log(res)

        if(res.data.errmsg!=''){
          this.setData({
            isFavorite: true,
          })
        } else {
          this.setData({
            isFavorite: false,
          })
        }
      })
    })
  },

  judgeFavorite(){
    wx.getStorage({
      key: 'user_id',
      success: (res) => {
        this.judgeMusic(res.data)
      },
    })
  },


  addFavorites(event){
    wx.getStorage({
      key: 'user_id',
      success: (res)=> {
        this.collectMusic(res.data)
        // console.log(res)
        this.setData({
          isFavorite: true,
        })
      },
      fail: (res)=>{
        this.setData({
          modalShow: true,
        })
      }
    })
  },

  onLoginsuccess(event) {
    this.setData({
      modalShow: false,
    }, () => {
      this.judgeFavorite()
    })
  },

  onLoginfail() {
    wx.showModal({
      title: '收藏需登录',
      content: '',
    });
  },

  /**  
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})